package com.web.app.ctrl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.web.app.dao.TaskMapper;
import com.web.app.dao.TaskWithStudentMapper;
import com.web.app.dao.UserMapper;
import com.web.app.pojo.Task;
import com.web.app.pojo.TaskWithStudent;
import com.web.app.pojo.User;
import com.web.app.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 任务管理表 前端控制器
 * </p>
 *
 * @author 林
 * @since 2022-09-21
 */
@RestController
@CrossOrigin
public class TaskController {

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TaskWithStudentMapper studentMapper;

    @RequestMapping("/getTasksByTeacherIdAndClassId")
    public ResultUtil getTasksByTeacherIdAndClassId(Task task){
        ResultUtil ok = ResultUtil.ok();
        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        if(task.getRelationTeacherId() != null){
            queryWrapper.eq("relation_teacher_id",task.getRelationTeacherId());
        }
        queryWrapper.eq("relation_class_id",task.getRelationClassId());

        List<Task> tasks = taskMapper.selectList(queryWrapper);
        ok.setData(tasks);
        return ok;
    }

    @RequestMapping("/editTask")
    public ResultUtil editTask(Task task){
        ResultUtil resultUtil = ResultUtil.ok();
        taskMapper.updateById(task);
        return resultUtil;
    }

    @RequestMapping("/delTask")
    public ResultUtil delTask(int id){
        ResultUtil resultUtil = ResultUtil.ok();
        taskMapper.deleteById(id);
        QueryWrapper<TaskWithStudent> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.eq("relation_task_id",id);
        studentMapper.delete(studentQueryWrapper);
        return resultUtil;
    }

    @RequestMapping("/addTask")
    public ResultUtil addTask(Task task){
        task.setStartTime(new Date());
        ResultUtil ok = ResultUtil.ok("添加成功");
        System.err.println(task.getId());
        int i = taskMapper.insert(task);
        System.err.println(task.getId());
        ok.setData(i);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_type",0);
        queryWrapper.eq("status",task.getRelationClassId());
        List<User> users = userMapper.selectList(queryWrapper);
        for(User user:users){
            TaskWithStudent student = new TaskWithStudent();
            student.setRelationStudentId(user.getId());
            student.setRelationTaskId(task.getId());
            studentMapper.insert(student);
        }
        return ok;
    }
}

